import Vue from 'vue'
import router from './router'
import store from './store'
import lodash from 'lodash'
import { setDocumentTitle, domTitle } from '@/utils/domUtil'
const routermaps = router.options.routes

/**
 * 递归查询route.config中配置的路由路径
 */
let RecursionFind = function(routes, menuitem) {
  if(lodash.isNil(routes)) return null;
  let routeitem = null;
  //DavidLee 2020/09/14 调整route查找优先级，匹配 route.config中配置meta.mapurl与menuitem.UrlRoute相匹配的页面
  routeitem = lodash.find(routes, (cfg) => { 
    if(cfg.meta === undefined) return false;
    else if(cfg.meta.mapurl === undefined) return false;
    else return cfg.meta.mapurl === menuitem.UrlRoute;
  })
  if(routeitem !== undefined) {
    routeitem.params = { columnid: menuitem.Id };
    return routeitem;
  }
  routeitem = null; //continue recursion find
  lodash.forEach(routes, function(item) {
    if (lodash.isNil(item.meta)) return false;
    if (!lodash.isNil(item.meta.mapurl)) {      
      if(item.meta.mapurl !== '') {
        routeitem = item.meta.mapurl === menuitem.UrlRoute ? item : RecursionFind(item.children, menuitem);
        if(routeitem !== null) return false;
      } else {
        if(menuitem.LayoutType === 1 && item.name === 'articledetail') { //单页详情
          routeitem = item;
          //通过后台栏目菜单UrlRoute匹配到vue route时，
          //如果栏目菜单为单页详情菜单，则设置参数articleid为0，进入详情页后通过栏目菜单ID获取对应文章Id
          //或根据栏目页面布局显示指定功能页面
          //如 栏目菜单为 "在线留言",则有可能该导航页面为提交用户留言信息，不需要显示指定文章或博客内容
          routeitem.params = { columnid: menuitem.Id, articleid: 0};
          return false;
        }
        else if(menuitem.LayoutType == 2 && item.name === 'articlelist') { //列表
          routeitem = item;
          routeitem.params = { columnid: menuitem.Id};
          return false;
        }
        else {
          routeitem = RecursionFind(item.children, menuitem)
          if(routeitem !== null) return false;
        }
      }
    } else {
      routeitem = RecursionFind(item.children, menuitem);
      if(routeitem !== null) return false;
    }
  });
  return routeitem;
}
//https://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript
let getQueryStringParams = query => {
  return query
      ? (/^[?#]/.test(query) ? query.slice(1) : query)
          .split('&')
          .reduce((params, param) => {
                  let [key, value] = param.split('=');
                  params[key] = value ? decodeURIComponent(value.replace(/\+/g, ' ')) : '';
                  return params;
              }, {}
          )
      : {}
};

router.beforeEach((to, from, next) => {
  if (store.getters.navmenus.length === 0) {
    const langid = to.meta.langid || 0
    store
      .dispatch('GetNavMenusAsync', langid)
      .then(menus => {        
        if(to.meta && to.meta.columntype){
          const columnmenus = lodash.filter(menus, function(m) { 
            if(!to.meta.columntype) return true;
            return m.ColumnType === 1 || m.ColumnType === to.meta.columntype;
          });
          store.commit('SET_NAVMENUS', columnmenus);
          if(!lodash.isNil(to.meta.mapurl)) { //适用于通过routeconfig所配置的url进行正向查询
            let menuitem = lodash.find(columnmenus, function(o) { return o.UrlRoute === to.meta.mapurl; });
            if(!lodash.isNil(menuitem))  {//适用于首页等链接固定页
              setDocumentTitle(`${menuitem.Name} - ${domTitle}`)
              store.commit('SET_LANGUAGE', menuitem.LanguageId, menuitem.LanguageCode)
              //DavidLee 通过routeconfig配置url正向查询时对可能需要使用到的链接参数做匹配
              if(!to.query.hasOwnProperty("columnid")) 
                to.query['columnid'] = menuitem.Id;
            }
            else if(to.name === 'articlelist' || to.name === 'articledetail') { //适用于带参数的动态路由(!lodash.isNil(to.params.columnid))
              menuitem = lodash.find(columnmenus, function(o) { 
                let cid = to.params.columnid;
                if(typeof to.params.columnid === 'string')
                  cid = parseInt(to.params.columnid)
                return o.Id === cid; 
              });
              if(!lodash.isNil(menuitem)) {
                setDocumentTitle(`${menuitem.Name} - ${domTitle}`)
                store.commit('SET_LANGUAGE', menuitem.LanguageId, menuitem.LanguageCode)
              }
              else {
                next({ name: 'Exception404' })
                return;
              }
            }
          } else if(to.redirectedFrom) { //适用于后台定义栏目菜单路由转换为routeconfig所配置的路由
            let params = {},
                urlPart = "",
                index = to.redirectedFrom.indexOf('?');
            if(index > 0) {
              urlPart = to.redirectedFrom.substring(0, index)
              params = getQueryStringParams(to.redirectedFrom.slice(index))
            } else urlPart = to.redirectedFrom;
            let menuitem = lodash.find(columnmenus, ['UrlRoute', urlPart]);
            if(menuitem !== undefined) {
              setDocumentTitle(`${menuitem.Name} - ${domTitle}`)
              store.commit('SET_LANGUAGE', menuitem.LanguageId, menuitem.LanguageCode)
              const redirectroute = RecursionFind(routermaps, menuitem)
              if(redirectroute !== null) {
                if(redirectroute.params !== undefined)
                  Object.assign(params, redirectroute.params)
                next({ name: redirectroute.name, params: params })
                return
              }
            }
          } 
        }
        // 请求带有 redirect 重定向时，登录自动重定向到该地址
        const redirect = decodeURIComponent(from.query.redirect || to.redirect || to.path)
        // 跳转到目的路由 **注： 注意vue-route跳转 path/query配对 name/params配对的区别
        next({ path: redirect, /*params:*/query: to.query })
      })
      .catch((err) => {
        console.error("GetNavMenus Api Error:" + err)
      })
  } else {
    if(to.redirectedFrom) {
      const menuitem = lodash.find(store.getters.navmenus, function(o) { return o.UrlRoute === to.redirectedFrom; });
      if(!lodash.isNil(menuitem)) {
        setDocumentTitle(`${menuitem.Name} - ${domTitle}`)
        store.commit('SET_LANGUAGE', menuitem.LanguageId, menuitem.LanguageCode)
        const redirectroute = RecursionFind(routermaps, menuitem)
        if(redirectroute !== null) { 
          next({ name: redirectroute.name, params: redirectroute.params })
          return
        }
      }
    }
    next()
  }
})

router.afterEach(() => {
  
})
